<template>
  <div class="user-header">
    <el-button
      type="primary"
      @click="handleAdd"
      v-if="permission.includes('user:add')"
      >新增</el-button
    >
    <el-form :inline="true" :model="formInline">
      <el-form-item>
        <el-input v-model="formInline.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="table">
    <el-table
      :data="tableData"
      style="width: 100%; --el-table-border: 1px solid #d6d9e1"
    >
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="username" label="用户名" width="140" />
      <el-table-column
        prop="nickname"
        label="昵称"
        width="140"
        show-overflow-tooltip
      />
      <el-table-column prop="phone" label="电话" width="140" />
      <el-table-column prop="icon" label="头像">
        <template #default="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="200" />
      <el-table-column prop="update_time" label="更新时间" width="200" />
      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #="scope">
          <el-button
            type="primary"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('user:update')"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('user:delete')"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            type="warning"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('user:resetPwd')"
            @click="updatepwd(scope.row)"
          >
            修改密码
          </el-button>
          <el-button
            type="warning"
            :disabled="scope.row.id == 1"
            size="small"
            v-if="permission.includes('user:role')"
            @click="showAssignRole(scope.row)"
          >
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="pager"
      :page-size="config.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="config.total"
      @size-change="handleSizeChange"
      @current-change="handleChange"
    />
  </div>

  <!-- 新增弹出框内容 -->
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="35%"
  >
    <el-form :model="formUser" :rules="rules" ref="userForm">
      <el-form-item v-if="false" prop="id">
        <el-input v-model="formUser.id" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formUser.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input v-model="formUser.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="action == 'add'">
        <el-input v-model="formUser.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="formUser.phone" placeholder="请输入电话" />
      </el-form-item>
      <!-- 头像上传部分保持不变 -->
      <el-form-item label="头像" prop="icon">
        <el-upload
          class="avatar-uploader"
          action="https://xychp.jxnews.com.cn:9906/api/Index/upload"
          name="annex[]"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <!-- 重点：直接使用 formUser.icon 显示头像 -->
          <img v-if="formUser.icon" :src="formUser.icon" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 修改密码弹出框内容 -->
  <el-dialog v-model="dialogPwdVisible" title="修改密码" width="35%">
    <el-form :model="formPwd" :rules="pwdRules" ref="pwdForm">
      <el-form-item prop="id" v-show="false">
        <el-input v-model="formPwd.id" />
      </el-form-item>
      <el-form-item label="修改密码" prop="password">
        <el-input v-model="formPwd.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="repwd">
        <el-input v-model="formPwd.repwd" placeholder="请输入再次输入密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleCancelPwd">取消</el-button>
        <el-button type="primary" @click="onSubmitPwd">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogRoleVisible" center title="分配角色" width="40%">
    <el-form label-width="80px">
      <!-- 禁止修改 -->
      <el-form-item label="用户名">
        <el-input disabled v-model="sysUser.username"></el-input>
      </el-form-item>
      <el-form-item label="角色列表">
        <el-select
          multiple
          v-model="addRoleForm.role_ids"
          placeholder="角色列表"
          size="large"
        >
          <el-option
            v-for="item in tableRoleData"
            :key="item.id"
            :label="item.role_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="addRole" type="primary">提交</el-button>
        <el-button @click="dialogRoleVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  onMounted,
  reactive,
  nextTick,
  watch,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  userList,
  addUser,
  updateUser,
  deleteUser,
  updatePassword,
  uploadImg,
  AllRole,
  assignRole,
  getUserRoles,
} from "@/api/index.js";
import { useAllDataStore } from "@/stores";
import { Plus } from "@element-plus/icons-vue";
// const { proxy } = getCurrentInstance();
//新增或编辑的弹窗
const dialogVisible = ref(false); // 假设你有一个 dialogVisible 变量
const action = ref("add"); // 假设你有一个 action 变量
const imageUrl = ref("");
let addRoleForm = ref({});
let allDataStore = useAllDataStore();
let permission = ref(allDataStore.state.permissionList);

watch(dialogVisible, (newValue) => {
  if (!newValue) {
    imageUrl.value = ""; // 只重置 imageUrl ✅
  }
});
const handleAvatarSuccess = (response) => {
  if (response.code == 200) {
    imageUrl.value = response.data.file_paths[0]; // 更新预览图
    formUser.icon = response.data.file_paths[0]; // 同步到表单数据
  } else {
    ElMessage.error(response.msg);
  }
};
//表单校验规则
const rules = reactive({
  username: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
  password: [{ required: true, message: "密码是必填项", trigger: "blur" }],
  phone: [{ required: true, message: "电话是必选项", trigger: "blur" }],
  nickname: [{ required: true, message: "昵称是必选项", trigger: "blur" }],
});

const userForm = ref(null);
const formUser = reactive({
  id: "",
  nickname: "",
  username: "",
  password: "",
  phone: "",
  icon: "",
});

const handleReset = () => {
  formInline.username = "";
  config.username = "";
  getUserData();
};

////弹窗关闭
const handleCancel = () => {
  userForm.value.resetFields();
  dialogVisible.value = false;
  imageUrl.value = ""; // 关闭弹窗时清除预览
};

//新增窗口
const handleAdd = () => {
  dialogVisible.value = true;
  Object.keys(formUser).forEach((key) => {
    formUser[key] = "";
  });
  action.value = "add";
};

const onSubmit = async () => {
  if (action.value === "add") {
    addUser(formUser).then((data) => {
      if (data.data.code === 200) {
        ElMessage.success("成功");
        handleCancel();
        getUserData();
      } else {
        ElMessage.error(data.data.msg);
      }
    });
  } else if (action.value === "edit") {
    // 创建一个不包含 password 的新对象
    const { password, ...userData } = formUser;
    updateUser(userData).then((data) => {
      if (data.data.code === 200) {
        ElMessage.success("成功");
        handleCancel();
        getUserData();
      } else {
        ElMessage.error(data.data.msg);
      }
    });
  } else {
    ElMessage.error("操作失败");
  }
};

const formInline = reactive({
  username: "",
});

const config = reactive({
  username: "",
  total: 0,
  page: 1,
  pageSize: 10,
});

const handleSearch = () => {
  config.username = formInline.username;
  config.page = 1; // 重置为第一页
  getUserData();
};

const tableData = ref([]);
const tableRoleData = ref([]);

//获取用户列表
const getUserData = async () => {
  try {
    const { data } = await userList(config);
    tableData.value = data.data.data;
    config.total = data.data.total;
  } catch (error) {
    console.error("获取用户数据失败", error);
  }
};
// 角色分配相关状态
const sysUser = ref({}); // 当前操作的用户
let addRole = () => {
  assignRole({
    ...addRoleForm.value,
    user_id: sysUser.value.id,
    ...sysUser.value,
  }).then((data) => {
    if (data.data.code === 200) {
      dialogRoleVisible.value = false;
      ElMessage.success("分配成功");
    }
  });
};
//获取全部角色列表
const getAllRole = async () => {
  try {
    const { data } = await AllRole(config);
    tableRoleData.value = data.data.data;
    config.total = data.data.total;
  } catch (error) {
    console.error("获取用户数据失败", error);
  }
};
const handleChange = (page) => {
  config.page = page;
  getUserData();
};

const handleSizeChange = (size) => {
  config.pageSize = size;
  getUserData();
};

// 删除方法
const handleDelete = async (val) => {
  try {
    await ElMessageBox.confirm("确定删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteUser({ ids: [val.id] });

    // ⚠️ 根据你后端返回结构调整这里
    const data = response.data || response;

    // console.log("返回结果：", data);

    if (data.code === 200) {
      ElMessage({
        showClose: true,
        type: "success",
        message: "删除成功",
      });
      getUserData(); // ✅ 刷新表格数据
    } else {
      ElMessage.error(data.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败，请查看控制台");
      console.error("删除失败：", error);
    }
  }
};

const handleEdit = (val) => {
  action.value = "edit";
  dialogVisible.value = true;
  nextTick(() => {
    Object.assign(formUser, { ...val });
    imageUrl.value = formUser.icon; // 同步头像路径到 imageUrl ✅
  });
};

const dialogPwdVisible = ref(false);
//修改以密码
const updatepwd = (val) => {
  dialogPwdVisible.value = true;
  formPwd.id = val.id;
};
const formPwd = reactive({
  id: "",
  password: "",
  repwd: "",
});

const handleCancelPwd = () => {
  formPwd.password = "";
  formPwd.repwd = "";
  dialogPwdVisible.value = false;
};

const pwdRules = reactive({
  password: [{ required: true, message: "密码是必填项", trigger: "blur" }],
  repwd: [{ required: true, message: "确认密码是必填项", trigger: "blur" }],
});

const onSubmitPwd = () => {
  updatePassword(formPwd).then((data) => {
    if (data.data.code === 200) {
      ElMessage.success("成功");
      handleCancelPwd();
      getUserData();
    } else {
      ElMessage.error(data.data.msg);
    }
  });
};

const allRoles = ref([]); // 所有角色列表
// 角色列表
const userRoleIds = ref([]);

const dialogRoleVisible = ref(false);
const showAssignRole = async (row) => {
  getUserRoles({ user_id: row.id }).then((data) => {
    if (data.data.code === 200) {
      addRoleForm.value.role_ids = data.data.data.map((item) => {
        return item.id;
      });
    }
  });

  sysUser.value = row;
  dialogRoleVisible.value = true;
};

// let DepartmentList = [];
onMounted(() => {
  getUserData();
  getAllRole();
});
</script>
<style scoped lang="less">
.user-header {
  display: flex;
  justify-content: space-between;
}

.table {
  position: relative;
  // height: 520px;
  background-color: #fff;

  .pager {
    // position: absolute;
  }

  .el-table {
    // height: 500px;
    width: 100%;
  }
}

:deep(.el-form-item__content) {
  justify-content: center;
}
.avatar {
  width: 100px;
  height: 100px;
}
</style>
